package com.ythook.mentor.service;

import com.ythook.mentor.entity.RegisterVo;
import com.ythook.mentor.entity.User;
import com.ythook.mentor.repository.UserRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class UserService {
    @Resource
    private UserRepository userRepository;

    public List<User> search() {
        return userRepository.findAll();
    }

    public List<User> searchMentorByKey(Date startDate, Date endDate, String key) {
        List<User> list_user = userRepository.searchMentorByKey(startDate, key);
        return list_user;
    }

    public Optional<User> findById(Long id) {
        return userRepository.findById(id);
    }
    public void delete(Long id) {
        userRepository.deleteById(id);
    }

    public User add(User user) {
        return userRepository.save(user);
    }
    public User update(User user) {
        if(!StringUtils.isEmpty(user.getPassword())){
            return userRepository.save(user);
        }else {
            Optional<User> tmpUser = this.findById(user.getId());
            user.setPassword(tmpUser.get().getPassword());
            return userRepository.save(user);
        }
    }

    public User register(RegisterVo registerVo) {
        User user = new User();
        BeanUtils.copyProperties(registerVo, user);
        user.setUserStatus("1");
        return userRepository.save(user);
    }

    public User login(String username, String password) {
        return userRepository.login(username, password);
    }
}
